package com.example.socket;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @Author 郅占伟
 * @ClassName ReceiveData
 * @Description TODO
 * @Date 2024年05月25日
 * @Version: 1.0
 */
public class ReceiveData {
    public static void main(String[] args) {
        Socket socket = null;
        try {
            socket = new Socket("localhost", 8888); // 主机地址和端口号
            OutputStream outputStream = socket.getOutputStream();   // 获取输出流
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);   // 将输出流包装成DataOutputStream

            dataOutputStream.writeUTF("这里是客户端，收到请回复");   // 发送数据
            InputStream inputStream = socket.getInputStream();   // 获取输入流
            DataInputStream dataInputStream = new DataInputStream(inputStream);   // 将输入流包装成DataInputStream

            String s = dataInputStream.readUTF();   // 接收数据
            System.out.println("客户端接收到的数据：[" + s + "]");

            // 关闭流
            dataInputStream.close();
            dataOutputStream.close();
            socket.close();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}